<?php
/**
 *  session mysql 数据库存储类
 *
 * @copyright			(C) 2011-11-11 CLOUD
 * @license				
 * 
 */
class Session_SessionMysql extends Model
{
	/**
	 * 有效期
	 * @var int
	 */
	private $lifetime = 1800;

    public function __construct()
    {
    	$this->tableName = 'sessions';
    	parent::__construct();
    	session_set_save_handler( array( & $this , 'open' ) , array( & $this , 'close'), array( & $this , 'read' ) , array( & $this ,'write' ) , array( & $this , 'destroy' ) , array( & $this ,'gc' ) );
    	session_cache_limiter('private, must-revalidate');
    	session_start();
    }
    
	/**
	 * session_set_save_handler  open方法
	 * @param $save_path
	 * @param $session_name
	 * @return true
	 */
    public function open( $save_path , $session_name ) 
    {
		return true;
    }
    
	/**
	 * session_set_save_handler  close方法
	 * @return bool
	 */
    public function close() 
    {
        return $this->gc( $this->lifetime );
    } 
    
	/**
	 * 读取session_id
	 * @return string session_id
	 */
    public function read( $id ) 
    {
		$r = $this->getOne( array( 'session_id' => $id ) , 'data' );
		return $r ? $r['data'] : '';
    } 
    
	/**
	 * 写入session_id 的值
	 * 
	 * @param $id session
	 * @param $data 值
	 * @return mixed query 执行结果
	 */
    public function write( $id , $data ) 
    {
		$ip = Ip::getCurrentIP();
		$sessiondata = array(
							'session_id' => $id,
							'ip' => $ip,
							'lastvisit' => SYSTIME,
							'data' => $data,
						);
		return $this->insert( $sessiondata , true , true );
    }
	/** 
	 * 删除指定的session_id
	 * 
	 * @param $id session
	 * @return bool
	 */
    public function destroy( $id ) 
    {
		return $this->delete( array( 'session_id' => $id ) );
    }
    
	/**
	 * 删除过期的 session
	 * 
	 * @param $maxlifetime 存活期时间
	 * @return bool
	 */
	public function gc( $maxlifetime ) 
	{
		$expiretime = SYSTIME - $maxlifetime;
		return $this->delete( "`lastvisit`<$expiretime " );
    }
}
?>